import WxRequest from '../assets/plugins/wx-request/lib/index'
import __cache from '../etc/cache'
import __config from '../etc/config'
import CryptoService from 'CryptoService'

class HttpService extends WxRequest {
  __cache

  constructor(options, isShowToast, checkLogin) {
    super(options);
    this.$$prefix = ''
    console.log(options, isShowToast)
    this.$$path = {
      user: {
        trOpenIdByCode: '/user/trOpenIdByCode',
        updateUserInfo: '/user/updateUserInfo',
        postFormId: '/user/postFormId',
        updateFormIdCancel: '/user/updateFormIdCancel',
        getUser: '/user/getUserInfo',
        updateTelephone: '/user/updateTelephone',
        selectTelephone: '/user/selectTelephone',
        getSessionKey: '/user/getSessionKey',
        updateUserChannelByShare: '/user/updateUserChannelByShare',
        login: '/user/loginByMini'
      },
      yanshuo:{
        getCommentGoods:'/commentGoodsWeb/getCommentGoods',
        putComment:'/commentGoodsWeb/putComment',
        putLikeComment:'/commentGoodsWeb/putLikeComment',
        getCommentByCommentId: '/commentGoodsWeb/getCommentByCommentId',
        putFavorite:'/commentGoodsWeb/putFavorite',
        getGoodsByClass:'/commentGoodsWeb/getGoodsByClass',
        putSkin:'/commentGoodsWeb/putSkin',
        getSkin: '/commentGoodsWeb/getSkin',
        getCommentByUser:'/commentGoodsWeb/getCommentByUser',
        getFavoriteByUser:'/commentGoodsWeb/getFavoriteByUser'
      },

    };
    this.interceptors.use({//请求的总入口
      request(request) {
        let userId = wx.getStorageSync(__cache.userId)
        if (checkLogin) {
          const App = getApp();
          if (userId == '' || userId == undefined) {
            if (App.data.canIUse){
              App.showLogin(true)
            }
          } else {
            App.showLogin(false)
          }
        }
        request.header = request.header || {}
        request.header['content-type'] = 'application/x-www-form-urlencoded'
        request.header['userId'] = wx.getStorageSync(__cache.userId)
        request.header['merchantId'] = __config.merchantId
        request.header['version'] = __config.version
        if (isShowToast) {
          wx.showLoading({
            title: '加载中',
          })
        }

        return request
      },
      requestError(requestError) {
        wx.hideLoading()
        return Promise.reject(requestError)
      },
      response(response) {
        wx.hideLoading()
        return response
      },
      responseError(responseError) {
        wx.hideLoading()
        return Promise.reject(responseError)
      },
    })
  }


  getOfflineActivityList(params) {
    console.log(params)
    return this.getRequest(`${this.$$path.offlineActivity.getList}`, {
      data: params,
    })
  }


  getOfflineActivityDetail(params) {
    console.log(params)
    return this.getRequest(`${this.$$path.offlineActivity.getDetail}`, {
      data: params,
    })
  }

  getActivityLocal(params) {
    return this.getRequest(`${this.$$path.activityLocal.getActivityLocal}`)
  }

  //goods
  getGoodsList(params) {
    return this.getRequest(`${this.$$path.goods.getGoodsList}`, {
      data: params,
    })
  }

  getGoodsDetail(goodId, params) {
    return this.getRequest(`${this.$$path.goods.getGoodsDetail}/${goodId}`, {
      data: params
    });
  }

  getGoodsById(goodId) {
    return this.getRequest(`${this.$$path.goods.getGoodsById}/${goodId}`);
  }

  getActivityDetail(params) {
    __cache.showLoading = false
    console.log("=====" + params)
    return this.getRequest(`${this.$$path.goods.getActivityDetail}`, {
      data: params
    });
  }

  getGoodsPresentDetail(params) {
    return this.getRequest(`${this.$$path.goods.getGoodsPresentDetail}`, {
      data: params
    });
  }

  getGroupListByActivityId(params) {
    return this.getRequest(`${this.$$path.goods.getGroupListByActivityId}/${params}`)
  }

  getActivityList(params) {
    return this.getRequest(`${this.$$path.goods.getActivityList}`, {
      data: params
    });
  }


  //cart
  getCartByUser() {
    return this.getRequest(`${this.$$path.cart.getCartList}`)
  }



  getNews(newsId) {
    return this.getRequest(`${this.$$path.news.getNews}/` + newsId)
  }

  addCartByUser(goodsId, propertyId, buyNumber) {
    return this.postRequest(`${this.$$path.cart.addCart}`, {
      data: {
        goodsId: goodsId,
        propertyId: propertyId,
        buyNumber: buyNumber,
      }
    })
  }

  updateCartByUser(params) {
    return this.postRequest(`${this.$$path.cart.updateCart}`, {
      data: params
    })
  }

  testPay() {
    return this.postRequest(`${this.$$path.order.test}`, {})
  }

  queryPay(params) {
    return this.postRequest(`${this.$$path.order.payCallBack}`, {
      data: params
    })
  }
  updateUserChannelByShare(params) {
    return this.postRequest(`${this.$$path.user.updateUserChannelByShare}`, {
      data: params
    })
  }

  getRedRacket(params) {
    return this.postRequest(`${this.$$path.redpacket.getRedRacket}`, {
      data: params
    })
  }

  getRedRacketRecord(params) {
    return this.getRequest(`${this.$$path.redpacket.getRedRacketRecordList}`, {
      data: params
    });
  }

  delCartByUser(goodsId) {
    return this.deleteRequest(`${this.$$path.cart.delCart}/${goodsId}`)
  }

  clearCartByUser() {
    return this.postRequest(`${this.$$path.cart.clearCart}`)
  }


  addOrder(params) {
    return this.postRequest(`${this.$$path.order.addOrder}`, {
      data: params,
    })
  }

  getDiscount(selectParams, totalAmount) {
    return this.postRequest(`${this.$$path.order.getDiscount}`, {
      data: {
        selectParams: selectParams,
        totalAmount: totalAmount
      }
    });
  }

  getOrderDetail(orderId) {
    return this.getRequest(`${this.$$path.order.getOrder}`, {
      data: {
        orderId: orderId
      }
    });
  }

  cancelOrder(orderId) {
    return this.postRequest(`${this.$$path.cancelOrder}`, {
      data: {
        orderId: orderId
      }
    });
  }

  getOrderList(params) {
    return this.getRequest(`${this.$$path.order.getOrderList}`, {
      data: params
    });
  }

  getGroupsDetail(params) {
    return this.getRequest(`${this.$$path.groups.getDetail}`, {
      data: params
    });
  }

  getShareCouponList(shareCouponId) {
    return this.getRequest(`${this.$$path.coupon.getShareCouponList}`, {
      data: {
        shareCouponId: shareCouponId
      }
    })
  }

  joinShareCoupon(shareCouponId) {
    return this.getRequest(`${this.$$path.coupon.joinShareCoupon}/${shareCouponId}`)
  }

  beginShareCoupon() {
    return this.getRequest(`${this.$$path.coupon.beginShareCoupon}`)
  }

  isHasShareCouponByUserId() {
    return this.getRequest(`${this.$$path.coupon.isHasShareCouponByUserId}`)
  }

  getCurrentShareCouponId() {
    return this.getRequest(`${this.$$path.coupon.getCurrentShareCouponId}`)
  }

  getSelfCouponCount() {
    return this.getRequest(`${this.$$path.coupon.getSelfCouponCount}`)
  }

  getSelfCouponList() {
    return this.getRequest(`${this.$$path.coupon.getSelfCouponList}`)
  }

  getSelfCouponListByUse() {
    return this.getRequest(`${this.$$path.coupon.getSelfCouponListByUse}`)
  }


  getSelfCouponListByGoodsIds(goodsId) {
    return this.getRequest(`${this.$$path.coupon.getSelfCouponListByGoodsIds}`, {
      data: {
        goodsIds: goodsId
      }
    })
  }

  consumeCoupon(couponId) {
    return this.getRequest(`${this.$$path.coupon.consumeCoupon}`, {
      data: {
        couponId: couponId
      }
    })
  }


  getActivityCouponConfig(params) {
    return this.postRequest(`${this.$$path.coupon.getActivityCouponConfig}`, {
      data: params
    })
  }
  confirmCollectGoods(params) {
    return this.postRequest(`${this.$$path.order.confirmCollectGoods}`, {
      data: params
    })
  }

  activityGetCoupon(params) {
    return this.postRequest(`${this.$$path.coupon.activityGetCoupon}`, {
      data: params
    })
  }

  //保存formid
  postFormId(formId) {
    return this.postRequest(`${this.$$path.user.postFormId}`, {
      data: {
        formId: formId
      }
    });
  }

  postFormIdParam(params) {
    return this.postRequest(`${this.$$path.user.postFormId}`, {
      data: params
    });
  }

  updateFormIdCancel(params) {
    return this.postRequest(`${this.$$path.user.updateFormIdCancel}`, {
      data: params
    });
  }

  postFormIdParamByCoupon(params) {
    return this.postRequest(`${this.$$path.coupon.postFormId}`, {
      data: params
    });
  }


  bindgetuserinfo(bindUser, callBack) {
    var channel = wx.getStorageSync(__cache.channel);
    var shareChannel = wx.getStorageSync(__cache.shareChannel);
    wx.setStorageSync(__cache.user, bindUser.detail.userInfo);
    wx.login({
      success: (response) => {
        console.log('-----微信登录------');
        if (response && response.code) {
          var code = response.code;
          //获取用户信息
          wx.setStorageSync(__cache.user, bindUser.detail.userInfo);
          this.getRequest(`${this.$$path.user.getSessionKey}`, {
            data: {
              code: code,
            }
          }).then(res => {

            console.log(res);
            const App = getApp();
            App.showLogin(false)

            if (res.data.code == "1000" && bindUser.detail.iv) {
              let d = {
                appId: __config.appId,
                sessionKey: res.data.data.session_key,
                encryptedData: bindUser.detail.encryptedData,
                iv: bindUser.detail.iv
              };
              let data = new CryptoService().decrypt(d);
              console.log(data)
              //发起登录
              this.postRequest(`${this.$$path.user.login}`, {
                data: {
                  nickname: data.nickName,
                  avatarUrl: data.avatarUrl,
                  gender: data.gender,
                  province: data.province,
                  city: data.city,
                  unionId: data.unionId,
                  openId: data.openId,
                  channel: channel ? channel : "",
                  shareChannel: shareChannel ? shareChannel : ""
                }
              }).then(res => {
                console.log("login success === ", res)

                if (res.data.code === "1000") {
                  wx.setStorageSync(__cache.userId, res.data.data.userId);
                  if (callBack) {
                    callBack(bindUser.detail.userInfo)
                  }
                  const App = getApp();
                  App.showLogin(false)
                } else {
                  console.log("======授权失败======");
                }
              }).catch(error => {
                console.log("======授权失败======");
              });
            } else {
              //发起登录
              this.postRequest(`${this.$$path.user.login}`, {
                data: {
                  openId: res.data.data.openid,
                  unionId: res.data.data.unionid,
                  channel: channel ? channel : "",
                  shareChannel: shareChannel ? shareChannel : ""
                }
              }).then(res => {
                console.log("login success === ", res)

                if (res.data.code === "1000") {
                  wx.setStorageSync(__cache.userId, res.data.data.userId);
                  if (callBack) {
                    callBack(bindUser.detail.userInfo)
                  }

                } else {
                  console.log("======授权失败======");
                }
              }).catch(error => {
                console.log("======授权失败======");
              });
            }
          })

        } else {
          console.log("======授权失败======");
        }
      },
      fail: function (res) {
        console.log("调用登录接口失败" + res)
      }
    })
  }

  /**
   * 登录
   * @returns {Promise.<TResult>}
   */
  login() {
    return this.isLogin().then((response) => {
      console.log(" true ====")
      return true;
    }, (error) => {
      console.log("============ login")
      return this.getUserInfo();
    });
  }

  /**
   * 判断用户是否登录
   */
  isLogin() {
    return new Promise((resolve, reject) => {
      const userId = wx.getStorageSync(__cache.userId);
      if (!userId) {
        wx.clearStorageSync();
        return reject(false);
      }
      return resolve(true);
    });
  }

  getUserToken(code, encryptedData, iv, resolve, reject) {

    var channel = wx.getStorageSync(__cache.channel);
    //发起网络请求
    this.getRequest(`${this.$$path.user.getSessionKey}`, {
      data: {
        code: code,
      }
    }).then(res => {
      if (res.data.code === "1000") {
        let d = {
          appId: __config.appId,
          sessionKey: res.data.data.session_key,
          encryptedData: encryptedData,
          iv: iv
        };
        let data = new CryptoService().decrypt(d);
        console.log(data)
        //发起登录
        this.postRequest(`${this.$$path.user.login}`, {
          data: {
            nickname: data.nickName,
            avatarUrl: data.avatarUrl,
            gender: data.gender,
            province: data.province,
            city: data.city,
            unionId: data.unionId,
            openId: data.openId,
            channel: channel ? channel : ""
          }
        }).then(res => {
          if (res.data.code == "1000") {
            wx.setStorageSync(__cache.userId, res.data.data.userId);
            wx.setStorageSync(__cache.token, res.data.data.token);
            const App = getApp();
            App.globalData.userId = res.data.data.userId;
            resolve(res.userInfo);
          } else {
            console.log("======授权失败======");
            // reject(false)
          }
        }).catch(error => {
          // reject(false)
        });
      }
    })
  }

  //获取用户信息
  getUserInfo() {

    const userId = wx.getStorageSync(__cache.userId);
    if (userId) {
      return
    }

    let that = this;
    return new Promise((resolve, reject) => {
      wx.login({
        success: function (response) {
          console.log('-----微信登录------');
          console.log(response);
          if (response && response.code) {
            var code = response.code;
            //获取用户信息
            wx.getUserInfo({
              success: function (res) {
                console.log('-----用户信息------');
                wx.setStorageSync(__cache.user, res.userInfo);
                that.getUserToken(code, res.encryptedData, res.iv, resolve, reject)
              },
              fail: function (res) {
                console.log("拒绝授权", res)
              }
            })
          } else {
            reject(false);
          }
        },
        fail: function (res) {
          reject(false);
          console.log("调用登录接口失败" + res)
        }
      })
    });
  }

  getUser() {
    __cache.showLoading = false;
    return this.getRequest(`${this.$$path.user.getUser}`)
  }

  //商店
  getShopInfoList(params) {
    return this.getRequest(`${this.$$path.shop.getShopInfoList}`)
  }

  getGoodsClass(params) {
    return this.getRequest(`${this.$$path.goods.getGoodsClass}`, {
      data: params
    });
  }

  addAddressOrUpdate(params) {
    __cache.showLoading = false
    return this.putRequest(`${this.$$path.address.addOrUpdate}`, {
      data: params,
    })
  }

  getAddressDefault(params) {
    return this.getRequest(`${this.$$path.address.getDefault}`)
  }

  getExpress(params) {
    console.log(params)
    return this.getRequest(`${this.$$path.express.getExpress}`, {
      data: params,
    })
  }

  getHomeBanner(params) {
    return this.getRequest(`${this.$$path.advert.banner}`)
  }

  getRecommend(params) {
    __cache.showLoading = false
    return this.getRequest(`${this.$$path.goods.getRecommend}`, {
      data: params,
    })
  }

  updateUserTelephone(params) {
    console.log(params)
    return this.postRequest(`${this.$$path.user.updateTelephone}`, {
      data: params,
    })
  }

  selectUserTelephone(params) {
    return this.getRequest(`${this.$$path.user.selectTelephone}`)
  }

  getGongLue(params) {
    return this.postRequest(`${this.$$path.coupon.getGongLue}`)
  }

  getGrowGrass(params) {
    return this.getRequest(`${this.$$path.goods.getGrowGrass}`, {
      data: params
    })
  }

  putGrowGrass(params) {
    return this.postRequest(`${this.$$path.goods.putGrowGrass}`, {
      data: params
    })
  }

  getChouJiangConfig(params) {
    return this.getRequest(`${this.$$path.choujiang.getChouJiangConfig}`, {
      data: params
    })
  }

  getLuckNumber(params) {
    return this.getRequest(`${this.$$path.choujiang.getLuckNumber}`, {
      data: params
    })
  }

  getRecommendGenreList(params) {
    return this.getRequest(`${this.$$path.goods.getRecommendGenreList}`, {
      data: params
    })
  }

  getJoinUserList(params) {
    return this.getRequest(`${this.$$path.choujiang.getJoinUserList}`, {
      data: params
    })
  }
  getCommentGoods(params) {
    return this.getRequest(`${this.$$path.yanshuo.getCommentGoods}`, {
      data: params
    })
  }
  putComment(params) {
    return this.postRequest(`${this.$$path.yanshuo.putComment}`, {
      data: params
    })
  }
  putLikeComment(params) {
    return this.postRequest(`${this.$$path.yanshuo.putLikeComment}`, {
      data: params
    })
  }
  getCommentByCommentId(params) {
    return this.getRequest(`${this.$$path.yanshuo.getCommentByCommentId}`, {
      data: params
    })
  }
  putFavorite(params) {
    return this.postRequest(`${this.$$path.yanshuo.putFavorite}`, {
      data: params
    })
  }
  getGoodsByClass(params) {
    return this.getRequest(`${this.$$path.yanshuo.getGoodsByClass}`, {
      data: params
    })
  }
  putSkin(params){
    return this.postRequest(`${this.$$path.yanshuo.putSkin}`, {
      data: params
    })
  }
  getSkin(params) {
    return this.getRequest(`${this.$$path.yanshuo.getSkin}`, {
      data: params
    })
  }
  getCommentByUser(params) {
    return this.getRequest(`${this.$$path.yanshuo.getCommentByUser}`, {
      data: params
    })
  }
  getFavoriteByUser(params) {
    return this.getRequest(`${this.$$path.yanshuo.getFavoriteByUser}`, {
      data: params
    })
  }
}

export default HttpService